package jp.sourceforge.akjrcp.image.gifanime;

import com.akjava.lib.standards.process.ProcessPrinter;

import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jp.sourceforge.akjrcp.akj_betas.Akj_betasPlugin;
import jp.sourceforge.akjrcp.akj_betas.Messages;
import jp.sourceforge.akjrcp.commons.ui.EditableFileList;
import jp.sourceforge.akjrcp.commons.ui.FileDirChoicer;
import jp.sourceforge.akjrcp.commons.ui.FileDirChoicer2;
import jp.sourceforge.akjrcp.commons.ui.AbstractFileDirChoicer.FileStatusChangeEvent;
import jp.sourceforge.akjrcp.commons.ui.AbstractFileDirChoicer.FileStatusChangeListener;
import jp.sourceforge.akjrcp.commons.ui.widget.WidgetBuilder;
import jp.sourceforge.akjrcp.ffmpeg.FFMpegUtils;
import jp.sourceforge.akjrcp.ffmpeg.SimpleCommandExecuter;
import jp.sourceforge.akjrcp.tools.OtherToolsSettingPage;
import jp.sourceforge.akjrcp.ui.LayoutDataBuilder;
import jp.sourceforge.akjrcp.ui.SimpleImageCanvas;
import jp.sourceforge.akjrcp.ui.param.ParamCombo;
import jp.sourceforge.akjrcp.ui.param.ParamScale;
import jp.sourceforge.akjrcp.util.ExecutingControler;
import jp.sourceforge.akjrcp.util.SelectionUtils;
import jp.sourceforge.akjrcp.util.StatusBarUtils;
import jp.sourceforge.akjrcp.util.ExecutingControler.ExecutingControlButton;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/*
 * on IE seems bad.
 * last frame never called.
 */
public class GifAnimeMakeView extends ViewPart {
	public static Log log=LogFactory.getLog(GifAnimeMakeView.class);
	
	public static final String ID = GifAnimeMakeView.class.getName();

	private EditableFileList fileList;
	
	private MakeGifAnimeExecute executer;
	private FileDirChoicer exportGifChoicer;

	private ParamScale delayScale;

	private ParamScale loopScale;
	private ParamCombo sizeCombo;



	private SimpleImageCanvas imageCanvas;

	private FileSelected selectedListener=new FileSelected();
	
	public EditableFileList getFileList(){
		return fileList;
	}
	public void createPartControl(Composite parent) {
		parent.setLayout(new GridLayout());
		executer=new MakeGifAnimeExecute();
		Composite split2=WidgetBuilder.createGridLayoutComposite(parent,SWT.NULL,2,false);
		split2.setLayoutData(LayoutDataBuilder.fillBothGridData());
		fileList = WidgetBuilder.createFileList(split2,SWT.BORDER,"*.gif;*.png;*.jpg;*.bmp");
		fileList.setLayoutData(LayoutDataBuilder.hintGridData(300, -1));
		fileList.setInput(this.getSite());
		fileList.addPropertyChangeListener(new IPropertyChangeListener(){

			public void propertyChange(PropertyChangeEvent event) {
				executer.updateControlSwitch();
			}});
		fileList.addSelectionChangedListener(new ISelectionChangedListener(){

			public void selectionChanged(SelectionChangedEvent event) {
				ISelection selection=event.getSelection();
				
				File selectFile=SelectionUtils.getSelectFile(selection);
				if(selectFile!=null){
					imageCanvas.setImagePath(selectFile.getAbsolutePath());
				}else{
					imageCanvas.setImagePath(null);
				}
			}});
		
		imageCanvas = new SimpleImageCanvas(split2);
		imageCanvas.setLayoutData(LayoutDataBuilder.fillBothGridData());
		/*
		FigureCanvas canvas = new FigureCanvas(split2);
		canvas.setLayoutData(LayoutDataBuilder.fillBothGridData());
		rootLbel = new Label();
		//root.setIcon(new Image(null,"c:\\tmp\\ppm.jpg"));
		canvas.setContents(rootLbel);
		*/
		Composite split=WidgetBuilder.createGridLayoutComposite(parent, SWT.NULL,2,false);
		split.setLayoutData(LayoutDataBuilder.fillHorizontalGridData());
		delayScale = new ParamScale(split,SWT.NULL,"delay_scale",Messages.getString("gifanimeview.delay"));
		
		delayScale.setMinimum(0);
		delayScale.setMaximum(1000);
		delayScale.setValue(10);
		delayScale.setLayoutData(LayoutDataBuilder.fillHorizontalGridData());
		delayScale.getScale().setLayoutData(LayoutDataBuilder.fillHorizontalGridData());
		loopScale = new ParamScale(split,SWT.NULL,"loop_scale",Messages.getString("gifanimeview.loop"));
		
		loopScale.setMinimum(0);
		loopScale.setMaximum(100);
		loopScale.setValue(1);
		
		sizeCombo=new ParamCombo(parent,SWT.NULL,"image_size",Messages.getString("gifanimeview.image_size"),new String[]{"","80","160","320","640"});
		
		exportGifChoicer=new FileDirChoicer(parent,SWT.NULL,FileDirChoicer2.SAVE,Messages.getString("gifanimeview.export_gif"));
		exportGifChoicer.setFilterExtensions(new String[]{"*.gif"});
		exportGifChoicer.setLayoutData(LayoutDataBuilder.fillHorizontalGridData());
		exportGifChoicer.addFileListChangeListener(selectedListener);//for update exec button
		
		//execute Button
		Composite exec_label=WidgetBuilder.createGridLayoutComposite(parent,SWT.NULL,2, false);
		ExecutingControlButton exec=new ExecutingControlButton(exec_label,SWT.NULL,executer,
				Messages.getString("gifanimeview.convert"),Messages.getString("cancel"));
		exec.setLayoutData(LayoutDataBuilder.hintGridData(100,40));
		executer.updateControlSwitch();
	}
	
	public void setFocus() {
		
	}
	
	

	public class MakeGifAnimeExecute extends ExecutingControler{
		File[] files;
		String exportPath;
		private int size;
		private int delay;
		private int loop;
		@Override
		public void afterExecute() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void beforeExecute() {
			files=fileList.getFileList();
			exportPath=exportGifChoicer.getAbsoluteFilePath();
			try{
			size=Integer.parseInt(sizeCombo.getValue());
			}catch(Exception e){log.warn("size-invalid:"+sizeCombo.getValue());}
			
			try{
				loop=Integer.parseInt(loopScale.getValue());
				}catch(Exception e){log.warn("loop-invalid:"+loopScale.getValue());}
				
				
				try{
					delay=Integer.parseInt(delayScale.getValue());
					}catch(Exception e){log.warn("delay-invalid:"+delayScale.getValue());}
		}

		@Override
		public boolean canExecute() {
			// TODO Auto-generated method stub
			boolean ret= fileList.getFileList().length>0 && !exportGifChoicer.getAbsoluteFilePath().equals("");
		
			return ret;
		}

		@Override
		public void cancelExecuting() {
			// TODO Auto-generated method stub
			
		}

		
		@Override
		public void inExecute() {
			//validate values
			if(files==null || files.length==0){
				Akj_betasPlugin.getDefault().getProcessPrinter().printError("files empty");
				return;
			}
			
			//
			StatusBarUtils.showStatusBar(Messages.getString("gifanimemakeview.start_convert"));
			String exePath=Akj_betasPlugin.getDefault().getPreferenceStore().getString(OtherToolsSettingPage.PATH_IMAGEMAGICK_CONVERT);
			if(exePath.equals("")){
				StatusBarUtils.showStatusBar(Messages.getString("gifanimemakeview.convert_not_found"));
				return;
			}
			
			
			List<String> list=new ArrayList<String>();
			
			list.add(exePath);
			
			if(size>0){
				list.add("-resize");
				list.add(""+size);
			}
			if(delay>0){
				list.add("-delay");
				list.add(""+delay);
			}
			if(loop>0){
				list.add("-loop");
				list.add(""+loop);
			}
			
			for (int i = 0; i < files.length; i++) {
				list.add(files[i].getAbsolutePath());
			}
			list.add(exportPath);
			/*
			if(vbr_value){
				list.add("-V");//vbr
			}
			list.add("-o");
			list.add(outputFileChooser_value);
			list.add(inputVideoFileChooser_value);
			
			
			if(!inputAudioFile1Chooser_value.equals("")){
				list.add(inputAudioFile1Chooser_value);
			}
			
			if(!inputAudioFile2Chooser_value.equals("")){
				list.add(inputAudioFile2Chooser_value);
			}*/
			
			String commands[]=list.toArray(new String[list.size()]);
			FFMpegUtils.toPrintCommand(commands);
			Akj_betasPlugin.getDefault().getProcessPrinter().printOutput("####\n");
			Akj_betasPlugin.getDefault().getProcessPrinter().printOutput(FFMpegUtils.toPrintCommand(commands)+"\n");
			SimpleCommandExecuter executer=new SimpleCommandExecuter(commands);
			CustomProcessPrinter printer=new CustomProcessPrinter(Messages.getString("gifanimemakeview.finish_convert"));
			executer.setPrinter(printer);
			
			executer.execute();
			StatusBarUtils.showStatusBar(printer.getResult());
			
			//some file check;
		}
		
	}
	
	public class CustomProcessPrinter implements ProcessPrinter{
		private String result="";
		public CustomProcessPrinter(String result){
			this.result=result;
		}
		public void printError(String error) throws IOException {
			print(error);
		}
		
		public void print(String text){
			Akj_betasPlugin.getDefault().getProcessPrinter().printOutput(text);
			String checkString="*faild*";
			if(text.indexOf(checkString)!=-1){
				result=Messages.getString("mplexviewer.faild");
			}
		}

		public void printOutput(String output) throws IOException {
			print(output);
		}

		public String getResult() {
			return result;
		}

		public void setResult(String result) {
			this.result = result;
		}
	}
	
	public class FileSelected implements FileStatusChangeListener{

		public void addList(FileStatusChangeEvent event) {
			executer.updateControlSwitch();
		}

		public void removeList(FileStatusChangeEvent event) {
			executer.updateControlSwitch();
		}
		
	}
		
}